#include <iostream>
#include "log.hpp"
#include "comm.hpp"

extern Log lg;
int main()
{
    Init init;
    int shmid = CreateShm();
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    int fd = open(FIFO_FILE, O_RDONLY);
    if (fd < 0)
    {
        lg(Fatal, "open fail,strerr:%s,errno code:%d", strerror(errno), errno);
        return 1;
    }
    // 开始通信
    struct shmid_ds shmds;
    char buffer[1024];
    while (true)
    {
        ssize_t s = read(fd, buffer, sizeof(buffer));
        if (s == 0)
        {
            lg(Debug,"read quit...");
            break;
        }
        else if (s < 0)
        {
            
            lg(Error,"read err,strerr:%s,error code:%d",strerror((errno)),errno);
            break;
        }
        else
        {
            buffer[s] = 0;
            std::cout << "client say# " << buffer << std::endl;
            sleep(1);
            // 监控，获取共享内存的元数据（大小，连接数，key，权限）
            shmctl(shmid, IPC_STAT, &shmds);
            std::cout << "shm size: " << shmds.shm_segsz << std::endl;
            std::cout << "shmds.shm_nattch" << shmds.shm_nattch << std::endl;
        }
    }
    shmdt(shmaddr);
    // 删除共享内存段
    shmctl(shmid, IPC_RMID, nullptr);
    close(fd);
    return 0;
}